package com.example.gitdemo2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketActvity extends AppCompatActivity {
    private Socket socket;
    private Button btnSend,btnConnect;
    private TextView textViewResponse;
    private EditText editTextMessage;
    private PrintWriter out;
    private BufferedReader in;
    private String serverAddress = "192.168.66.248";
    private int port = 8888;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_actvity);
        editTextMessage = findViewById(R.id.editTextMessage);
        textViewResponse = findViewById(R.id.textViewResponse);
        btnSend = findViewById(R.id.buttonSend);
        btnConnect = findViewById(R.id.buttonConnect);
    }
    //connect_socket
    public void connect_socket(View view) {
        new Thread(()->{
            try {
                socket = new Socket(serverAddress,port);
                out = new PrintWriter(socket.getOutputStream(),true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                runOnUiThread(()-> {
                    Toast.makeText(SocketActvity.this,"连接成功",Toast.LENGTH_SHORT).show();
                    btnConnect.setEnabled(false);
                    btnSend.setEnabled(true);
                });
            } catch (IOException e) {
                Toast.makeText(SocketActvity.this,"连接失败",Toast.LENGTH_SHORT).show();

                e.printStackTrace();
            }
        }).start();
    }
    public void send_socket(View view) {
        String mes = editTextMessage.getText().toString();
        if (mes.isEmpty()) {
            Toast.makeText(this, "请输入消息", Toast.LENGTH_SHORT).show();
            return;
        }
        new Thread(()-> {
            try {
                out.println(mes);
                String resp = in.readLine();
                runOnUiThread(()->textViewResponse.setText(resp));
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(()->Toast.makeText(SocketActvity.this,"发送失败",Toast.LENGTH_SHORT).show());
            }
        }).start();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭连接
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}